﻿using AntdUI;

namespace DataAcquisition
{
    public partial class DevicePointManageForm : BaseForm
    {
        #region 属性
        /// <summary>点位
        /// 
        /// </summary>
        private DevicePoint? obj;

        /// <summary>设备
        /// 
        /// </summary>
        public DeviceItem? deviceItem;
        #endregion

        #region 自定义方法

        /// <summary>列表
        /// 
        /// </summary>
        public void LoadList()
        {
            if (deviceItem is not null)
            {
                Dictionary<string, Object> where = new Dictionary<string, Object>();
                where["device_number"] = deviceItem.Number;
                List<DevicePoint> list = SqlHelper.Inquireable<DevicePoint>(where);
                UpdateTable(list);
            }
        }

        /// <summary>更新DataGridView
        /// 
        /// </summary>
        /// <param name="list"></param>
        private void UpdateTable(List<DevicePoint> list)
        {
            var antItemList = new List<DevicePointItem>();
            foreach (DevicePoint item in list)
            {
                string range = item.RangeMin.ToString() + "-" + item.RangeMax.ToString();
                string outValue = item.OutMin.ToString() + "-" + item.OutMax.ToString();
                string alarm = item.AlarmLow.ToString() + "-" + item.AlarmHight.ToString();
                string pointType = intToRegisterTypeString(item.PointType);

                antItemList.Add(new DevicePointItem(item.DeviceNumber, item.DeviceName, item.Number,
                                                    item.Name, item.Address, item.PointType, range, outValue,alarm, item.ErrorRange.ToString(), item.Amend,item.Unit));
            }
            Table1.DataSource = antItemList;
        }

        /// <summary>判断记录是否存在
        /// 
        /// </summary>
        /// <param name="number"></param>
        private bool CheckRowExist(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["number"] = number;
            List<DevicePoint> list = SqlHelper.Inquireable<DevicePoint>(where);
            if (list.Count > 0)
            {
                obj = list[0];
                return true;
            }
            else
            {
                string msg = string.Format("【{0}】设备点位不存在", number);
                Error(msg);
                obj = null;
                return false;
            }
        }

        /// <summary>寄存器类型
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private string intToRegisterTypeString(int type)
        {
            string registerType = "";
            if (type == 1)
            {
                registerType = "DI";
            }
            else if (type == 2)
            {
                registerType = "DO";
            }
            else if (type == 3)
            {
                registerType = "InputRegister";
            }
            else if (type == 4)
            {
                registerType = "HoldingRegister";
            }
            return registerType;
        }

        /// <summary> 查询设备
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private Device? InquireDevice(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["number"] = number;
            List<Device> list = SqlHelper.Inquireable<Device>(where);
            if (list.Count > 0)
            {
                return list[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary> 查询设备点位有无绑定界面
        /// 
        /// </summary>
        /// <param name="number"></param>
        /// <returns></returns>
        private bool InquireFormPoint(int number)
        {
            Dictionary<string, Object> where = new Dictionary<string, Object>();
            where["device_point_number"] = number;
            List<FormPoint> list = SqlHelper.Inquireable<FormPoint>(where);
            if (list.Count > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 系统方法
        public DevicePointManageForm()
        {
            InitializeComponent();
            Header.Text = "设备点位管理";
            FullScreen = true;
        }

        private void DevicePointManageForm_Load(object sender, EventArgs e)
        {
            Table1.Height = this.Height - StackPanel1.Height - Divider1.Height;
            if (deviceItem is not null)
            {
                string title = string.Format("【{0}】设备点位管理", deviceItem.Name);
                Header.Text = title;
                Device? device = InquireDevice(deviceItem.Number);
                if (device != null) 
                {
                    Table1.Columns = new AntdUI.ColumnCollection {
                        new AntdUI.Column("DeviceNumber","设备编号",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("DeviceName","设备名称",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Number","点位编号",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Name","点位名称",AntdUI.ColumnAlign.Center),
                         new AntdUI.Column("Address","点位地址",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("PointType","点位类型",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Range","量程范围",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("OutValue","输出范围",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Alarm","报警范围",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("ErrorRange","判断范围",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Amend","修正数值",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Unit","数据单位",AntdUI.ColumnAlign.Center),
                        new AntdUI.Column("Operation","操作",AntdUI.ColumnAlign.Center){ Width="120", LineBreak=true}
                    }; 
                    Table1.Spin("正在加载中...", (config) =>
                    {
                        LoadList();
                    });
                }
                else
                {
                    if (this.Owner is not null)
                    {
                        ManageDeviceForm frm = (ManageDeviceForm)this.Owner;
                        frm.LoadList();
                        string msg = string.Format("【{0}】设备不存在，无法编辑点位", deviceItem.Name);
                        frm.Error(msg);
                    }
                    this.Close();
                }
            }
            else
            {
                this.Close();
            }
        }
        #endregion

        #region 响应事件
        private void Table1_CellButtonClick(object sender, TableButtonEventArgs e)
        {
            if (e.Record is DevicePointItem data)
            {
                CellLink link = e.Btn;
                if (link.Id == "edit")
                {
                }
                else if (link.Id == "delete")
                {
                    bool res = CheckRowExist(data.Number);
                    if (!res)
                    {
                        return;
                    }

                    res = InquireFormPoint(data.Number);
                    if (res)
                    {
                        Error(string.Format("【{0}】已绑定界面点位，无法删除", data.Name));
                        return;
                    }

                    string msg = string.Format("您确定要删除【{0}】点位吗？", data.Name);
                    AntdUI.Modal.open(new AntdUI.Modal.Config(this, "友情提示", msg)
                    {
                        OnOk = config =>
                        {
                            if (obj is not null)
                            {
                                
                                List<DevicePoint> list = new List<DevicePoint>();
                                list.Add(obj);
                                int deleteRes = SqlHelper.Deleteable(list);
                                if (deleteRes > 0)
                                {
                                    LoadList();
                                }
                                else
                                {
                                    Error("删除点位失败");
                                }
                            }
                            else
                            {
                                Error("删除点位失败");
                            }
                            return true;
                        },
                    });
                }
            }
        }

        /// <summary>添加设备点位
        /// 
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void AddDevicePointButton_Click(object sender, EventArgs e)
        {
            DevicePointAddForm frm = new DevicePointAddForm();
            frm.Owner = this;
            frm.deviceItem = deviceItem;
            frm.ShowDialog();
        }
        #endregion
    }
}
